package Utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.htmlcleaner.HtmlCleaner;




/* IP:InputStream
 * OP:pretty html file use for parse XML
 * Step:
 *  1. Detect charset from InputStream (Special with Tintuconline and Xaluan is alway UTF-8)
 *  2. Write to UTF-8 file
 *  3. Clear none-utf8 character
 *  4. Use HTML Cleaner to convert to XML 
 */

public class MakeHTMLFile{
 public static void MakeFile(InputStream in,String fileout) throws IOException{
  InputStream in1 = in;
  BufferedReader in2 = new BufferedReader(new InputStreamReader(in1,"UTF-8"));

  String line="";
  StringBuffer temp = new StringBuffer();
  while((line=in2.readLine())!=null){
   if(!line.trim().equals("")){
    temp.append(line);
    temp.append("\r\n");
   }
  }
  
  
  BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream(fileout, false), "UTF-8"));

  out.write(temp.toString());
  out.close();
 }
 public static void MakePrettyHTMLFile(String filein,String fileout){
  try{
       HtmlCleaner cleaner = new HtmlCleaner(new File(filein),"UTF-8");
      cleaner.setAllowHtmlInsideAttributes(true);
         cleaner.setUseEmptyElementTags(false);
         cleaner.setAdvancedXmlEscape(true);
         cleaner.setRecognizeUnicodeChars(true);
         cleaner.clean();
         cleaner.writePrettyXmlToFile(fileout, "UTF-8");
         
  }
  catch (IOException e) {
   e.printStackTrace();
  }
 }
}
